import cv2 as cv
import numpy as np

videoFilename = r'D:\opencv\opencv\sources\samples\data\vtest.avi'

cap = cv.VideoCapture(videoFilename)
fgbg = cv.createBackgroundSubtractorMOG2()
thresh = 200

while True:
    ret, frame = cap.read()
    if not ret: # 没读到当前帧，结束
        break

    fgmask =fgbg.apply(frame)
    _, fgmask = cv.threshold(fgmask, 30, 0xff, cv.THRESH_BINARY)

    bgImage = fgbg.getBackgroundImage()
    _, cnts, _ = cv.findContours(fgmask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

    count = 0
    n = 0
    for c in cnts:
        area = cv.contourArea(c)
        if(area < thresh): # 区域面积小于指定阈值
            continue
        count = 1
        n = n + count
        x, y, w, h, = cv.boundingRect(c)
        cv.rectangle(frame, (x, y), (x+w, y+h), (0, 0xff, 0), 2)
        cv.putText(frame, str(area), (x, y), cv.FONT_HERSHEY_PLAIN, 1, (0, 0xff, 0))
        print('目标', n, '\n', '位置为：', (x, y), '\n', '面积为', area, '\n')
    print('共监测到', n, '个目标', '\n')
    cv.imshow('frame', frame)
    cv.imshow('Background', bgImage)

    key = cv.waitKey(30)
    if key == 27: # 按下ESC键， 退出
        break

cap.release()
cv.destroyAllWindows()